import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { visualizer } from "rollup-plugin-visualizer";
import compression from "vite-plugin-compression";
import cdn from "vite-plugin-cdn-import";

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    visualizer({ open: true }), // bundle 分析
    compression({
      verbose: true, // 是否在控制台中输出压缩结果
      disable: false,
      threshold: 10240, // 如果体积大于阈值，将被压缩，单位为b，体积过小时请不要压缩，以免适得其反
      algorithm: "gzip", // 压缩算法，可选['gzip'，' brotliccompress '，'deflate '，'deflateRaw']
      ext: ".gz",
      deleteOriginFile: true, // 源文件压缩后是否删除(我为了看压缩后的效果，先选择了true)
    }), // GZIP 压缩
    cdn({
      modules: [
        "vue",
        "vue-router",
        "axios",
        "lodash",
        "dayjs",
        {
          name: "echarts",
          var: "echarts",
          path: "//cdn.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js",
        },
        {
          name: "element-plus",
          var: "ElementPlus",
          path: "//cdn.jsdelivr.net/npm/element-plus",
          css: "//cdn.jsdelivr.net/npm/element-plus/dist/index.css",
        },
        {
          name: "pinia",
          var: "pinia",
          path: "//cdn.jsdelivr.net/npm/pinia@next",
        },
        {
          name: "normalize.css",
          var: "normalize",
          path: "",
          css: "//cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css",
        },
      ],
    }),
  ],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  build: {
    rollupOptions: {
      // 确保外部化处理那些你不想打包进库的依赖
      external: [
        "vue",
        "vue-router",
        "axios",
        "lodash",
        "dayjs",
        "echarts",
        "ElementPlus",
        "normalize",
        "pinia",
      ],
      output: {
        chunkFileNames: "js/[name]-[hash].js", // 引入文件名的名称
        entryFileNames: "js/[name]-[hash].js", // 包的入口文件名称
        assetFileNames: "[ext]/[name]-[hash].[ext]", // 资源文件像 字体，图片等
        manualChunks: (chunk) => {
          if (chunk.includes("normalize.css")) {
            return "normalize";
          }
          console.log(chunk);
          return "vendor";
        },
      },
    },
  },
});
